package com.stsolutions.budgetcontroller.model.data;

import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
import com.stsolutions.budgetcontroller.util.FormatDate;

@DatabaseTable(tableName = "cost_bucket")
public class CostBucket {
	/**
	 * 
	 */

	@DatabaseField(generatedId = true)
	private int costBucketId;

	@DatabaseField
	private Date startCostControl;

	@DatabaseField
	private Date endCostControl;

	@ForeignCollectionField(eager = true)
	private Collection<Cost> costs;

	@DatabaseField
	private double totalBudgetPerBucket;

	public CostBucket() {
		costs = new LinkedList<Cost>();
	}

	public double getTotalBudgetPerBucket() {
		return totalBudgetPerBucket;
	}

	public void setTotalBudgetPerBucket(double totalBudgetPerBucket) {
		this.totalBudgetPerBucket = totalBudgetPerBucket;
	}

	public Date getStartCostControl() {
		return startCostControl;
	}

	public void setStartCostControl(Date startCostControl) {
		this.startCostControl = startCostControl;
	}

	public Date getEndCostControl() {
		return endCostControl;
	}

	public void setEndCostControl(Date endCostControl) {
		this.endCostControl = endCostControl;
	}

	public void addCost(Cost cost) {
		if (costsOverBudget()) {
			System.err.println("Budget exceeded for: " + cost.getCostValue()
					+ " EUR");
		}
		costs.add(cost);
	}

	private boolean costsOverBudget() {
		return getAvailableSum() <= 0;
	}

	public double getAvailableSum() {
		double totalCostsValue = 0;
		for (Cost cost : costs) {
			totalCostsValue += cost.getCostValue();
		}
		return (totalBudgetPerBucket - totalCostsValue);
	}

	public int getCostBucketId() {
		return costBucketId;
	}

	public void setCostBucketId(int costBucketId) {
		this.costBucketId = costBucketId;
	}

	public String toString() {
		return "From: " + FormatDate.formatDate(getStartCostControl())
				+ " To: " + FormatDate.formatDate(getEndCostControl())
				+ " budget: " + getAvailableSum();
	}

	public String printCosts() {
		StringBuilder sb = new StringBuilder();
		for (Cost cost : costs) {
			sb.append(cost.toString());
			sb.append('\n');
		}
		sb.append(this.toString());
		return sb.toString();
	}

	public Collection<Cost> getCosts() {
		return costs;
	}

	public void setCosts(Collection<Cost> costs) {
		this.costs = costs;
	}
}
